import tkinter as tk
from tkinter import messagebox, ttk
import redis
import utils

class CustomerManagement:
    def __init__(self, parent):
        self.parent = parent
        self.create_widgets()
        self.load_customers()

    def create_widgets(self):
        self.frame = tk.Frame(self.parent)
        self.frame.pack(fill=tk.BOTH, expand=True)

        # 主 Treeview 和滚动条
        self.tree_frame = tk.Frame(self.frame)
        self.tree_frame.pack(fill=tk.BOTH, expand=True)

        self.tree_scrollbar_y = tk.Scrollbar(self.tree_frame, orient=tk.VERTICAL)
        self.tree_scrollbar_y.pack(side=tk.RIGHT, fill=tk.Y)

        self.tree_scrollbar_x = tk.Scrollbar(self.tree_frame, orient=tk.HORIZONTAL)
        self.tree_scrollbar_x.pack(side=tk.BOTTOM, fill=tk.X)

        self.tree = ttk.Treeview(self.tree_frame, columns=("Cid", "CcompanyName", "CcompanySName", "CcompanyAddress", "CcompanyPhone", "Cemail", "Cname", "CtelPhone", "other"), 
                                 show='headings', yscrollcommand=self.tree_scrollbar_y.set, xscrollcommand=self.tree_scrollbar_x.set)
        self.tree.heading("Cid", text="客户编号")
        self.tree.heading("CcompanyName", text="客户名称")
        self.tree.heading("CcompanySName", text="客户简称")
        self.tree.heading("CcompanyAddress", text="地址")
        self.tree.heading("CcompanyPhone", text="公司电话")
        self.tree.heading("Cemail", text="邮件")
        self.tree.heading("Cname", text="联系人")
        self.tree.heading("CtelPhone", text="联系人电话")
        self.tree.heading("other", text="备注")
        self.tree.pack(fill=tk.BOTH, expand=True)
        self.tree_scrollbar_y.config(command=self.tree.yview)
        self.tree_scrollbar_x.config(command=self.tree.xview)

        self.tree.bind("<<TreeviewSelect>>", self.on_tree_select)

        self.button_frame = tk.Frame(self.parent)
        self.button_frame.pack(fill=tk.X)

        self.add_button = tk.Button(self.button_frame, text="添加", command=self.add_customer)
        self.add_button.pack(side=tk.LEFT, padx=5, pady=5)

        self.update_button = tk.Button(self.button_frame, text="更新", command=self.update_customer)
        self.update_button.pack(side=tk.LEFT, padx=5, pady=5)

        self.delete_button = tk.Button(self.button_frame, text="删除", command=self.delete_customer)
        self.delete_button.pack(side=tk.LEFT, padx=5, pady=5)

        self.export_button = tk.Button(self.button_frame, text="导出到.csv", command=self.export_customers)
        self.export_button.pack(side=tk.LEFT, padx=5, pady=5)

    def load_customers(self):
        self.tree.delete(*self.tree.get_children())
        r = redis.StrictRedis(host='localhost', port=6379, db=0, decode_responses=True)
        customers = r.hgetall('tb_customer')
        for cid, customer in customers.items():
            customer_data = eval(customer)
            self.tree.insert("", "end", values=(cid, customer_data['CcompanyName'], customer_data['CcompanySName'], customer_data['CcompanyAddress'], customer_data['CcompanyPhone'], customer_data['Cemail'], customer_data['Cname'], customer_data['CtelPhone'], customer_data['other']))

    def on_tree_select(self, event):
        selected_items = self.tree.selection()
        if selected_items:
            selected_item = selected_items[0]
            self.selected_customer = self.tree.item(selected_item, "values")
        else:
            self.selected_customer = None

    def add_customer(self):
        self.customer_popup("添加客户", self.save_new_customer)

    def update_customer(self):
        if hasattr(self, 'selected_customer') and self.selected_customer:
            self.customer_popup("更新客户", self.save_updated_customer, self.selected_customer)
        else:
            messagebox.showwarning("警告", "请先选择一个客户")

    def delete_customer(self):
        if hasattr(self, 'selected_customer') and self.selected_customer:
            r = redis.StrictRedis(host='localhost', port=6379, db=0, decode_responses=True)
            r.hdel('tb_customer', self.selected_customer[0])
            self.load_customers()
        else:
            messagebox.showwarning("警告", "请先选择一个客户")

    def export_customers(self):
        r = redis.StrictRedis(host='localhost', port=6379, db=0, decode_responses=True)
        customers = r.hgetall('tb_customer')
        utils.export_to_csv(customers, 'customers.csv')

    def customer_popup(self, title, save_command, customer_data=None):
        popup = tk.Toplevel(self.parent)
        popup.title(title)
        popup.geometry("600x600")

        fields = ["Cid", "CcompanyName", "CcompanySName", "CcompanyAddress", "CcompanyPhone", "Cemail", "Cname", "CtelPhone", "other"]
        entries = {}

        for field in fields:
            tk.Label(popup, text=field).pack(pady=5)
            entry = tk.Entry(popup)
            entry.pack(pady=5)
            entries[field] = entry

        if customer_data:
            for i, field in enumerate(fields):
                entries[field].insert(0, customer_data[i])
                if field == "Cid":
                    entries[field].config(state='readonly')  # 使ID字段只读
        else:
            new_cid = self.generate_id('Cid')
            entries["Cid"].insert(0, new_cid)
            entries["Cid"].config(state='readonly')  # 使ID字段只读

        tk.Button(popup, text="保存", command=lambda: save_command(entries, popup)).pack(pady=20)

    def save_new_customer(self, entries, popup):
        try:
            customer_data = {field: entry.get() for field, entry in entries.items()}
            r = redis.StrictRedis(host='localhost', port=6379, db=0, decode_responses=True)
            r.hset('tb_customer', customer_data['Cid'], str(customer_data))
            self.load_customers()
            popup.destroy()
        except Exception as e:
            messagebox.showerror("Error", f"无法保存客户: {e}")

    def save_updated_customer(self, entries, popup):
        try:
            customer_data = {field: entry.get() for field, entry in entries.items()}
            r = redis.StrictRedis(host='localhost', port=6379, db=0, decode_responses=True)
            r.hset('tb_customer', customer_data['Cid'], str(customer_data))
            self.load_customers()
            popup.destroy()
        except Exception as e:
            messagebox.showerror("Error", f"无法更新客户: {e}")

    def generate_id(self, prefix):
        r = redis.StrictRedis(host='localhost', port=6379, db=0, decode_responses=True)
        current_id = r.incr('Cid_counter') + 999  # 从1000开始
        cid = f"gys{current_id:04d}"
        return cid

if __name__ == "__main__":
    root = tk.Tk()
    app = CustomerManagement(root)
    root.mainloop()
